package com.opensso.login.ctrl;

import com.opensso.core.entity.BeanRet;
import com.opensso.core.enums.SessionEnum;
import com.opensso.core.exceptions.BaseException;
import com.opensso.core.tools.StringTools;
import com.opensso.sessioin.service.SessionSV;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * Created by lixin on 2018/8/2.
 */
@RestController
@RequestMapping("/login")
@Slf4j
@Api(value = "登录控制器", description = "登录控制器")
public class LoginCtrl {

    @Resource
    private SessionSV sessionSV;

    /**
     * 登录系统
     * 1.获取request参数
     * 2.会话构建
     * 3.创建header信息以及cookie信息
     *
     * @param account  账户
     * @param password 密码
     * @return BeanRet
     */
    @ApiOperation(value = "查询DomainLog一个详情信息", notes = "查询DomainLog一个详情信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "账户", required = true, dataType = "java.lang.String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "java.lang.String", paramType = "query")
    })
    @GetMapping(value = "/signin")
    @ResponseBody
    public BeanRet login(String account, String password, HttpServletRequest request, HttpServletResponse response) {
        //1.获取request参数
        String clientIp = request.getRemoteHost();
        String serverIp = request.getServerName();
        StringBuffer url = request.getRequestURL();
        String requestUrl = request.getRequestURI();
        String domain = StringTools.getDomain(url, requestUrl);
        Locale locale = request.getLocale();

        //2.会话构建
        String refreshToken = sessionSV.build(account, password, clientIp, serverIp, locale.getLanguage(), requestUrl, domain.replaceAll(":\\d+", ""));
        log.info(refreshToken);

        //3.创建header信息以及cookie信息
        response.addHeader(SessionEnum.RefreshToken.name(), refreshToken);

        return BeanRet.create(true, BaseException.BaseExceptionEnum.Success, (Object) refreshToken);
    }

}
